package com.lingfengerick.commons.encrypt.sm2tool;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author lingfengerick
 * @since 2022/9/6 09:27
 */
public class SM2KeyPair {

    /**
    * 生成密钥对算法
    * @author  lingfengerick
    * @since  2022/9/21  15:50
    * @param algorithm 算法模式
    * @return 密钥对对象
    * @throws NoSuchAlgorithmException 异常
    * @throws InvalidAlgorithmParameterException 异常
    *
    */
    public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        ECGenParameterSpec sm2p256v1 = new ECGenParameterSpec("sm2p256v1");
        SecureRandom secureRandom = new SecureRandom();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm, new BouncyCastleProvider());
        keyPairGenerator.initialize(256, secureRandom);
        keyPairGenerator.initialize(sm2p256v1, secureRandom);
        return keyPairGenerator.generateKeyPair();
    }

    /**
    * 生成公钥对象
    * @author  lingfengerick
    * @since  2022/9/21  15:51
    * @param publicKey 公钥串
    * @return PublicKey 公钥对象
    *
    */
    public static PublicKey createPublicKey(String publicKey){
        PublicKey publickey = null;
        try {
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(publicKey));
            KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
            publickey = keyFactory.generatePublic(publicKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publickey;
    }

    /**
    * 生成私钥对象
    * @author  lingfengerick
    * @since  2022/9/21  15:51
    * @param privateKey 私钥串
    * @return 私钥对象
    *
    */
    public static PrivateKey createPrivateKey(String privateKey) {
        PrivateKey publickey = null;
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
            publickey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publickey;
    }
}
